package com.example.business.handler;

import com.example.business.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
// 登录成功处理器：认证成功后生成Token并返回
public class JwtLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, 
                                       HttpServletResponse response, 
                                       Authentication authentication) throws IOException {
        // 1. 从认证信息中获取用户名（authentication是Spring Security认证成功后生成的对象）
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        
        // 2. 调用JWT工具类生成Token（使用之前定义的JwtUtils）
        String token = JWTUtil.generateAccessToken(username);
        log.info("onAuthenticationSuccess: " + token);
        // 3. 设置响应格式（JSON），并返回Token给客户端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":200,\"msg\":\"登录成功\",\"token\":\"" + token + "\"}");
    }
}